package king.dominic.jlibrary.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

/**
 * Created by DominicKing on 2017/8/30.
 * KillHook
 */

public class KillHook {
    private static final String LOG_TAG = KillHook.class.getName();

    public static void go(final String pkg) {
        if (new Root().isDeviceRooted()) {
            HashSet<String> list = getSoList(pkg);
            for (String osPath : list) {
                uninstall(osPath);
            }
        }
    }

    private static HashSet<String> getSoList(final String pkg) {
        HashSet<String> temp = new HashSet<>();
        File file = new File("/proc/" + android.os.Process.myPid() + "/maps");
        if (!file.exists()) {
            return temp;
        }

        try {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file)));
            String lineString = null;
            while ((lineString = bufferedReader.readLine()) != null) {
                String tempString = lineString.trim();
                if (tempString.contains("/data/data")
                        && !tempString.contains("/data/data/" + pkg)) {
                    int index = tempString.indexOf("/data/data");
                    temp.add(tempString.substring(index));
                }
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static native void uninstall(String soPath);
}
